//
//  SISSHousePriceMapViewController.m
//  SISSAPP
//
//  Created by 袁应荣 on 2018/10/22.
//  Copyright © 2018年 优房网. All rights reserved.
//

#import "SISSHousePriceMapViewController.h"
#import <BaiduMapAPI_Base/BMKBaseComponent.h>//引入base相关所有的头文件
#import <BaiduMapAPI_Map/BMKMapComponent.h>//引入地图功能所有的头文件
#import <BaiduMapAPI_Utils/BMKUtilsComponent.h>//引入计算工具所有的头文件
#import "SISSRoundAnnotation.h"
#import "SISSPriceMessageAnnotation.h"
#import "SISSRoundAnnotationView.h"
#import "SISSPriceMessageAnnotationView.h"
#import "SISSHousePriceMapViewController+InitUI.h"
#import "SISSHousePriceMapViewController+DataRequest.h"
#import "SISSMapManager.h"
#import "SISSMapTownInfoModel.h"
#import "SISSRecommendPriceViewController.h"
#import "SISSPriceMapSearchViewController.h"

@interface SISSHousePriceMapViewController ()

//
@property (nonatomic, strong) NSMutableArray *zoneArr;
/// 判断是否是搜索点击返回的
@property (assign, nonatomic) BOOL isSearchBack;

@end

@implementation SISSHousePriceMapViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"城市房价地图";
    self.isSell = YES;

    UIBarButtonItem *searchItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(searchClickAction)];
    self.navigationItem.rightBarButtonItem = searchItem;
    
    [self requestDataWithMapSearchLevel:@"1"];
    
    [self setupUI];
    [self locationPrivilege];
    
}

- (void)searchClickAction {
    self.isSearchBack = NO;
    SISSPriceMapSearchViewController *vc = [[SISSPriceMapSearchViewController alloc] init];
    vc.selectCellBlock = ^(SISSMapBuildInfoModel * _Nonnull mapBuildInfo) {
        self.isSearchBack = YES;
        self.mapBuildInfoArr = @[mapBuildInfo];
        CLLocationCoordinate2D coordinate;
        NSArray *arr = [mapBuildInfo.mapPoint componentsSeparatedByString:@","];
        coordinate.longitude = [arr.firstObject floatValue];
        coordinate.latitude = [arr.lastObject floatValue];
        [self.mapView setCenterCoordinate:coordinate animated:NO];
        [self.mapView setZoomLevel:17];
//        [self mapView:self.mapView regionDidChangeAnimated:YES];
        
        [self loadDataWithZoomLevel:17];
    };
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


#pragma mark -- SISSMapPriceBottomShowViewDelegate
- (void)detailsButtonClickActionWithTownNo:(NSString *)townNo blockNo:(NSString *)blockNo {
    SISSRecommendPriceViewController *vc = [[SISSRecommendPriceViewController alloc] init];
    vc.isMapIn = YES;
    if (townNo.length > 0 && blockNo.length == 0) {
        vc.townNo = townNo;
    } else if (townNo.length == 0 && blockNo.length > 0) {
        vc.blockNo = blockNo;
    }
    
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark -- BMKMapViewDelegate

- (void)mapView:(BMKMapView *)mapView regionWillChangeAnimated:(BOOL)animated {
    self.zoomValue = mapView.zoomLevel;
    self.oldCoor = mapView.centerCoordinate;
    NSLog(@"之前的比例尺：%f",mapView.zoomLevel);
    
}

- (void)mapView:(BMKMapView *)mapView regionDidChangeAnimated:(BOOL)animated {
    
    NSLog(@"更改了区域");
    NSLog(@"当前比例尺%f，过去比例尺：%f",mapView.zoomLevel,self.zoomValue);
   
    if (mapView.zoomLevel > self.zoomValue) {
        NSLog(@"地图放大了");
        
        if (mapView.zoomLevel >= 13 && mapView.zoomLevel < 13.5) {
            if (!self.firstZoomUpRequestSuccess) {
                [self requestDataWithMapSearchLevel:@"1"];
            }
            self.firstZoomDownRequestSuccess = NO;
        } else if (mapView.zoomLevel >= 15 && mapView.zoomLevel < 15.5) {
            if (!self.secondZoomUpRequestSuccess) {
                [self requestDataWithMapSearchLevel:@"2"];
            }
            self.secondZoomDownRequestSuccess = NO;
        }
    } else if (mapView.zoomLevel < self.zoomValue){
        NSLog(@"地图缩小了");
        if (mapView.zoomLevel >= 13 && mapView.zoomLevel < 13.5) {
            if (!self.firstZoomDownRequestSuccess) {
                [self requestDataWithMapSearchLevel:@"1"];
            }
            self.firstZoomUpRequestSuccess = NO;
        } else if (mapView.zoomLevel >= 15 && mapView.zoomLevel < 15.5) {
            if (!self.secondZoomDownRequestSuccess) {
                [self requestDataWithMapSearchLevel:@"2"];
            }
            self.secondZoomUpRequestSuccess = NO;
        }
    }
    
    if (mapView.zoomLevel >= 17) {
        // 当前屏幕中心点的经纬度
        CGFloat centerLongitude = self.mapView.region.center.longitude;
        CGFloat centerLatitude = self.mapView.region.center.latitude;
        // 当前屏幕显示范围的经纬度
        CLLocationDegrees pointssLongitudeDelta = self.mapView.region.span.longitudeDelta;
        CLLocationDegrees pointssLatitudeDelta = self.mapView.region.span.latitudeDelta;
   
        CGFloat maxLon = centerLongitude + pointssLongitudeDelta / 2.0;
        CGFloat maxLat = centerLatitude + pointssLatitudeDelta /  2.0;
        CGFloat minLat = centerLatitude - pointssLatitudeDelta / 2.0;
        CGFloat minLon = centerLongitude - pointssLongitudeDelta / 2.0;
        
        NSLog(@"\n minLon   %f\n minLati  %f \n maxLon %f\n  maxLati  %f",minLon,minLat,maxLon,maxLat);
        self.maxLat = [NSString stringWithFormat:@"%lf",maxLat];
        self.minLat = [NSString stringWithFormat:@"%lf",minLat];
        self.maxLon = [NSString stringWithFormat:@"%lf",maxLon];
        self.minLon = [NSString stringWithFormat:@"%lf",minLon];
        
        if (!self.isSearchBack) {
            [self requestDataWithMapSearchLevel:@"3"];
        } else if (mapView.zoomLevel < self.zoomValue) {
            self.isSearchBack = NO;
        }
    }
    
    
    [self loadDataWithZoomLevel:mapView.zoomLevel];
    
    /// 点击大头针加载数据的时候不改变
    if (!self.selectPointShow) {
        [UIView animateWithDuration:1 animations:^{
            [self.priceBottomShowView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.bottom.equalTo(self.mas_bottomLayoutGuideTop).offset(200);
            }];
        }];
    }
}


- (void)loadDataWithZoomLevel:(NSInteger)zoomLevel {
//    WeakSelf
    [self.mapView removeAnnotations:self.zoneArr];
    if (zoomLevel < 15) {
        for (NSInteger i = 0; i < self.mapTownInfoArr.count; i++) {
            
            SISSRoundAnnotation *an = [[SISSRoundAnnotation alloc] init];
            CLLocationCoordinate2D coor;
            SISSMapTownInfoModel *model = self.mapTownInfoArr[i];
            
            NSArray *arr = [model.mapPoint componentsSeparatedByString:@","];
            coor.longitude = [arr.firstObject floatValue];
            coor.latitude = [arr.lastObject floatValue];
            an.type = 1;
            an.coordinate = coor;
            an.title = model.townName;
            an.subtitle = self.isSell ? model.sellPrice : model.rentPrice;
            an.Id = model.townNo;
            
            [self.zoneArr addObject:an];
            [self.mapView addAnnotation:an];
        }
    } else if (zoomLevel > 16.99) {
        for (NSInteger i = 0; i < self.mapBuildInfoArr.count; i++) {
            
            SISSPriceMessageAnnotation *an = [[SISSPriceMessageAnnotation alloc] init];
            CLLocationCoordinate2D coor;
            SISSMapBuildInfoModel *model = self.mapBuildInfoArr[i];
            
            NSArray *arr = [model.mapPoint componentsSeparatedByString:@","];
            coor.longitude = [arr.firstObject floatValue];
            coor.latitude = [arr.lastObject floatValue];
            an.type = 3;
            an.coordinate = coor;
            an.buildInfoModel = model;
            an.title = model.pname;
            [self.zoneArr addObject:an];
            [self.mapView addAnnotation:an];
        }
    } else {
        for (NSInteger i = 0; i < self.mapBlockInfoArr.count; i++) {
            
            SISSRoundAnnotation *an = [[SISSRoundAnnotation alloc] init];
            CLLocationCoordinate2D coor;
            SISSMapBlockInfoModel *model = self.mapBlockInfoArr[i];
            
            NSArray *arr = [model.mapPoint componentsSeparatedByString:@","];
            coor.longitude = [arr.firstObject floatValue];
            coor.latitude = [arr.lastObject floatValue];
            an.type = 2;
            an.coordinate = coor;
            an.title = model.blockName;
            an.subtitle = self.isSell ? model.sellPrice : model.rentPrice;
            an.Id = model.blockNo;
            
            [self.zoneArr addObject:an];
            [self.mapView addAnnotation:an];
        }
    }
    
}


// 使用苹果原生库计算两个经纬度直接的距离
- (double)distanceBetweenFromCoor:(CLLocationCoordinate2D)coor1 toCoor:(CLLocationCoordinate2D)coor2 {
    CLLocation *curLocation = [[CLLocation alloc] initWithLatitude:coor1.latitude longitude:coor1.longitude];
    CLLocation *otherLocation = [[CLLocation alloc] initWithLatitude:coor2.latitude longitude:coor2.longitude];
    double distance  = [curLocation distanceFromLocation:otherLocation];
    return distance;
}

// 点击了大头针
- (void)mapView:(BMKMapView *)mapView didSelectAnnotationView:(BMKAnnotationView *)view {
    if (view.annotation.coordinate.latitude == self.userLocation.location.coordinate.latitude) { // 个人位置特殊处理，否则类型不匹配崩溃
        NSLog(@"点击了个人位置");
        return;
    }
    SISSRoundAnnotation *annotation = (SISSRoundAnnotation *)view.annotation;
    
    if (annotation.type == 3) {
        
        SISSPriceMessageAnnotationView *messageAnnoView = (SISSPriceMessageAnnotationView *)view;
        
//        SISSPriceMessageAnnotation *annotation =
        SISSRecommendPriceViewController *vc = [[SISSRecommendPriceViewController alloc] init];
        vc.isMapIn = YES;
        vc.communityName = messageAnnoView.title;
        [self.navigationController pushViewController:vc animated:YES];
        // 计算距离 --> 请求列表数据 --> 完成 --> 展示表格
        //  self.communityId = annotationView.Id;
        
    } else if (annotation.type == 2) {
        self.blockNo = annotation.Id;
//        self.maxLat = [NSString stringWithFormat:@"%lf",annotation.coordinate.latitude + 0.01];
//        self.minLat = [NSString stringWithFormat:@"%lf",annotation.coordinate.latitude - 0.01];
//        self.maxLon = [NSString stringWithFormat:@"%lf",annotation.coordinate.longitude + 0.01];
//        self.minLon = [NSString stringWithFormat:@"%lf",annotation.coordinate.longitude - 0.01];
        self.mapBuildInfoArr = @[];
        self.selectPointShow = YES;
        [UIView animateWithDuration:1 animations:^{
            [self.priceBottomShowView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.bottom.equalTo(self.mas_bottomLayoutGuideTop).offset(0);
            }];
        }];
        // 点击了区域--->进入小区
        // 拿到大头针经纬度，放大地图。然后重新计算小区
        self.region = annotation.title;
        [mapView setCenterCoordinate:annotation.coordinate animated:NO];
        [mapView setZoomLevel:17];
        
    } else if (annotation.type == 1) {
        
        self.townNo = annotation.Id;
        self.maxLat = @"";
        self.minLat = @"";
        self.maxLon = @"";
        self.minLon = @"";
        self.mapBlockInfoArr = @[];
//        SISSRoundAnnotationView *roundAnno = (SISSRoundAnnotationView *)view;
        // 点击了区域--->进入小区
        // 拿到大头针经纬度，放大地图。然后重新计算小区
        self.region = annotation.title;
        [mapView setCenterCoordinate:annotation.coordinate animated:NO];
        [mapView setZoomLevel:15];
        self.selectPointShow = YES;
        [UIView animateWithDuration:1 animations:^{
            [self.priceBottomShowView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.bottom.equalTo(self.mas_bottomLayoutGuideTop).offset(0);
            }];
        }];
        [self mapView:mapView regionDidChangeAnimated:YES];
        
    }
}
- (void)mapView:(BMKMapView *)mapView didDeselectAnnotationView:(BMKAnnotationView *)view {
    
    if (view.annotation.coordinate.latitude == self.userLocation.location.coordinate.latitude) { // 个人位置特殊处理，否则类型不匹配崩溃
        NSLog(@"点击了个人位置");
        return;
    }
    
    SISSRoundAnnotation *annotationView = (SISSRoundAnnotation *)view.annotation;
    if (annotationView.type == 3) {
//        SISSPriceMessageAnnotationView *messageAnno = (SISSPriceMessageAnnotationView *)view;
        annotationView.messageAnnoIsBig = @"yes";
//        [messageAnno didDeSelectedAnnotation:messageAnno];
        [mapView mapForceRefresh];
    }
}


#pragma mark - Getter & Setter

- (NSMutableArray *)zoneArr {
    if (!_zoneArr) {
        _zoneArr = [NSMutableArray array];
    }
    return _zoneArr;
}


@end
